"""
配置管理模块
负责应用程序的配置管理，包括默认设置和用户偏好
使用JSON格式存储配置
"""
import json
import os
import logging

class ConfigManager:
    def __init__(self, config_file="config.json"):
        self.config_file = config_file
        self.logger = logging.getLogger(__name__)
        self.data = self._load_config()
    
    def _load_config(self):
        """加载配置文件，如果不存在则创建默认配置"""
        default_config = {
            "database": {
                "path": "data/schedules.db",
                "backup_on_start": True,
                "auto_cleanup_days": 30
            },
            "reminder": {
                "check_interval": 30,  # 秒
                "default_advance_minutes": 15,
                "play_sound": True,
                "sound_frequency": 1000,
                "sound_duration": 1000
            },
            "gui": {
                "window_width": 1000,
                "window_height": 700,
                "theme": "default",
                "font_size": 10,
                "auto_refresh": True
            },
            "export": {
                "default_format": "json",
                "auto_open_after_export": False,
                "export_directory": "data/exports"
            },
            "network": {
                "port": 8888,
                "auto_start_server": True,
                "timeout": 5
            },
            "system": {
                "log_level": "INFO",
                "max_log_files": 5,
                "max_backup_files": 10
            }
        }
        
        # 如果配置文件存在，加载用户配置
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    user_config = json.load(f)
                    # 深度合并配置
                    merged_config = self._deep_merge(default_config, user_config)
                    self.logger.info("配置文件加载成功")
                    return merged_config
            except Exception as e:
                self.logger.error(f"加载配置文件失败: {e}，使用默认配置")
                return default_config
        else:
            # 创建默认配置文件
            self._save_config(default_config)
            self.logger.info("创建默认配置文件")
            return default_config
    
    def _deep_merge(self, base, user):
        """深度合并两个字典"""
        result = base.copy()
        for key, value in user.items():
            if isinstance(value, dict) and key in result and isinstance(result[key], dict):
                result[key] = self._deep_merge(result[key], value)
            else:
                result[key] = value
        return result
    
    def _save_config(self, config=None):
        """保存配置到文件"""
        if config is not None:
            self.data = config
        
        try:
            # 确保配置文件的目录存在
            os.makedirs(os.path.dirname(os.path.abspath(self.config_file)), exist_ok=True)
            
            with open(self.config_file, 'w', encoding='utf-8') as f:
                json.dump(self.data, f, ensure_ascii=False, indent=2)
            self.logger.debug("配置已保存")
            return True
        except Exception as e:
            self.logger.error(f"保存配置失败: {e}")
            return False
    
    def get(self, key, default=None):
        """获取配置值，支持点分隔的键路径"""
        keys = key.split('.')
        value = self.data
        try:
            for k in keys:
                value = value[k]
            return value
        except (KeyError, TypeError):
            return default
    
    def set(self, key, value):
        """设置配置值，支持点分隔的键路径"""
        keys = key.split('.')
        config = self.data
        
        # 遍历到最后一个键的父级
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        
        # 设置最终值
        config[keys[-1]] = value
        return self._save_config()
    
    def reset_to_defaults(self):
        """重置为默认配置"""
        default_config = {
            "database": {
                "path": "data/schedules.db",
                "backup_on_start": True,
                "auto_cleanup_days": 30
            },
            "reminder": {
                "check_interval": 30,
                "default_advance_minutes": 15,
                "play_sound": True,
                "sound_frequency": 1000,
                "sound_duration": 1000
            },
            "gui": {
                "window_width": 1000,
                "window_height": 700,
                "theme": "default",
                "font_size": 10,
                "auto_refresh": True
            },
            "export": {
                "default_format": "json",
                "auto_open_after_export": False,
                "export_directory": "data/exports"
            },
            "network": {
                "port": 8888,
                "auto_start_server": True,
                "timeout": 5
            },
            "system": {
                "log_level": "INFO",
                "max_log_files": 5,
                "max_backup_files": 10
            }
        }
        
        self.data = default_config
        self._save_config()
        self.logger.info("配置已重置为默认值")
        return True
    
    def get_all_config(self):
        """获取所有配置"""
        return self.data.copy()

# 测试函数
def test_config():
    """测试配置管理器"""
    import tempfile
    
    # 使用临时文件测试
    with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
        temp_config_file = f.name
    
    try:
        # 创建配置管理器
        config = ConfigManager(temp_config_file)
        
        # 测试获取配置
        db_path = config.get("database.path")
        print(f"数据库路径: {db_path}")
        
        # 测试设置配置
        config.set("gui.window_width", 1200)
        new_width = config.get("gui.window_width")
        print(f"新窗口宽度: {new_width}")
        
        # 测试重置
        config.reset_to_defaults()
        default_width = config.get("gui.window_width")
        print(f"重置后窗口宽度: {default_width}")
        
        print("配置管理器测试通过!")
        
    finally:
        # 清理临时文件
        if os.path.exists(temp_config_file):
            os.unlink(temp_config_file)

if __name__ == "__main__":
    # 配置基础日志
    logging.basicConfig(level=logging.INFO)
    test_config()